package org.kamionowski.supreme.services.crawler.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kamionowski.supreme.persistence.dao.FileDAO;
import org.kamionowski.supreme.persistence.entity.File;
import org.kamionowski.supreme.persistence.entity.Service;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.sql.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Marcin Kamionowski
 * Date: 09.04.11
 * Time: 17:37
 */
@Component(value = "crawlerAnalyzer")
public class CrawlerAnalyzerImpl implements CrawlerAnalyzer {

    private final static Log log = LogFactory.getLog(CrawlerAnalyzerImpl.class);

    @Inject
    private FileDAO fileDAO;

    @Transactional
    @Override
    public void analyzeFile(RemoteFile remoteFile){
        log.debug("Analyze " + remoteFile);
        File file = fileDAO.searchByServiceAndPath(remoteFile.getService(), remoteFile.getFullPath());
        if(file == null){
            log.debug("File not exists in DB: " + remoteFile.getFullPath());
            file = new File();
            file.setModificationDate(new Date(remoteFile.getModificationDate()));
            file.setFileSize(remoteFile.getSize());
            file.setService(remoteFile.getService());
            file.setTmp(true);
            file.setMarked(false);
            file.setName(remoteFile.getFileName());
            file.setDir(remoteFile.getPath());
            fileDAO.insertFile(file);
        }else{
            log.debug("File exists in DB: " + remoteFile.getFullPath());
            file.setMarked(false);
            fileDAO.updateFile(file);
        }
    }

    @Override
    @Transactional
    public void preProcessing(Service service) {
        final int updatedRows = fileDAO.markFilesForService(service);
        log.info("Preprocessing success: marked files " + updatedRows + " for service " + service);
    }

    @Override
    public void postProcessing(Service service) {
        final int deletedRows = fileDAO.deleteMarkedFiles(service);
        log.info("Postprocessing success: deleted files " + deletedRows + " for service " + service);
    }

    public void setFileDAO(FileDAO fileDAO) {
        this.fileDAO = fileDAO;
    }
}
